package com.example.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.context.BaseContext;
import com.example.dto.FilesPageDTO;
import com.example.entity.Homework;
import com.example.entity.Login;
import com.example.entity.Modelfiles;
import com.example.mapper.HomeworkMapper;
import com.example.mapper.LoginMapper;
import com.example.mapper.ModelfilesMapper;
import com.example.result.PageResult;
import com.example.service.IModelfilesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.utils.BaseException;
import com.example.utils.CommonControllers;
import com.example.vo.BindfilesVO;
import com.example.vo.ModelfilesVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈昌吉
 * @since 2024-04-16
 */
@Service
public class ModelfilesServiceImpl extends ServiceImpl<ModelfilesMapper, Modelfiles> implements IModelfilesService {

    @Autowired
    private ModelfilesMapper modelfilesMapper;

    @Autowired
    private HomeworkMapper homeworkMapper;

    @Autowired
    private CommonControllers commonControllers;

    @Autowired
    private LoginMapper loginMapper;


    /**
     * 新增模型文件
     * @param file
     * @return
     */
    @Override
    public List<Modelfiles> insert(MultipartFile file,Integer hid) {

        //判断作业上交时间是否截止
        Homework homework = homeworkMapper.selectById(hid);
        System.out.println(LocalDateTime.now().isBefore(homework.getEndtime()));
        if (LocalDateTime.now().isBefore(homework.getEndtime())==false){
            throw new BaseException("作业时间已结束，不能在提交",500);
        }

        String originalFilename = file.getOriginalFilename();//获取文件原始名称
        //String s = FileUtil.mainName(originalFilename);//获取文件前面名不含后缀
        //String s1 = FileUtil.extName(originalFilename);//获取文件后缀名

        //判断文件名是否重复
        QueryWrapper<Modelfiles> wrapper = new QueryWrapper<>();
        List<Modelfiles> modelname = modelfilesMapper.selectList(wrapper.eq("name", originalFilename));
        if(modelname.size()!=0){
            throw new BaseException("该文件已存在，不能重复上传",500);
        }

        String upload = String.valueOf(commonControllers.upload(file));//获取返回的url

        //添加文件

        Modelfiles build = Modelfiles.builder()
                .url(upload)
                .hid(hid)
                .loginId(BaseContext.getCurrentId())
                .name(originalFilename)
                .uploadtime(LocalDateTime.now())
                .build();
        modelfilesMapper.insert(build);


        List<Modelfiles> modelfiles = modelfilesMapper.selectList(wrapper.eq("login_id", BaseContext.getCurrentId()).eq("hid",hid));

        return modelfiles;
    }

    /**
     * 获取当前作业下模型文件
     * @return
     */
    @Override
    public List<Modelfiles> select(Integer hid) {
        QueryWrapper<Modelfiles> wrapper = new QueryWrapper<>();
        List<Modelfiles> list = modelfilesMapper.selectList(wrapper.eq("hid",hid).eq("login_id",BaseContext.getCurrentId()));
        return list;
    }

    /**
     * 模型文件删除
     * @param modelfiles
     * @return
     */

    @Transactional
    @Override
    public String deleteModelFiles(Modelfiles modelfiles) {

        //删除oss上的文件
        String delete = commonControllers.delete(modelfiles.getUrl());
        //删除数据库数据
        modelfilesMapper.deleteById(modelfiles.getId());
        return delete;
    }

    /**
     * 审核模型文件获取相关接口
     * @param modelFilesPageDTO
     * @return
     */
    @Override
    public PageResult selectAll(FilesPageDTO modelFilesPageDTO) {
        //通过登录ID查询账号角色
        Login login = loginMapper.selectByID(BaseContext.getCurrentId());

        //判断当前角色0（老师）,1（助教）,2（学生）
        if (login.getRole().equals("0")){
            modelFilesPageDTO.setSta("合格");
        }else if (login.getRole().equals("1")){
            modelFilesPageDTO.setSta("待审核");
        }else{
            return null;
        }

        //1.设置分页参数
        PageHelper.startPage(modelFilesPageDTO.getPageNum(), modelFilesPageDTO.getPageSize());
        //开始分页查询
        Page<ModelfilesVO> page = modelfilesMapper.selectAll(modelFilesPageDTO.getHid(),modelFilesPageDTO.getSta(),modelFilesPageDTO.getState());

        long total = page.getTotal();
        List<ModelfilesVO> records = page.getResult();

        return new PageResult(total, records);

    }


    /**
     * 修改模型文件状态
     * @param modelfiles
     * @return
     */
    @Override
    public void updateModelFiles(Modelfiles modelfiles) {
        modelfilesMapper.updateModelFiles(modelfiles);
    }


}
